<template>
  <div class="tableListBox">
    <div class="blueTitleView">
      <div class="back" @click="back">
        <i class="vxe-icon-arrow-left" style="vertical-align: middle"></i>
        <span style="vertical-align: middle">返回</span>
      </div>
      <p class="titleview">项目收样台账</p>
    </div>
    <div class="iuapContent">
      <div class="content-form">
        <IuapSearch :fromData="fromData" @searchFn="(e) => {
          this.searchFn(e);
        }
          " @reset="(e) => {
    this.reset(e);
  }
    ">
        </IuapSearch>
      </div>
      <div class="content-form__operation">
        <vxe-button status="primary" size="small" @click="add">结算单生成</vxe-button>
        <vxe-button v-if="$route.query.contractStatus === 'IN_PROGRESS'" status="primary" size="small"
          @click="finish">合同完成</vxe-button>
      </div>
      <div class="tableList">
        <div class="onlyTable">
          <vxe-grid ref="table" resizable show-overflow row-key keep-source border :data="tableData" :columns="columns"
            max-height="100%" :span-method="rowspanMethod">
            <template #contractStatus="{ row }">
              <span>{{ row.contractStatus | getContractStatus }}</span>
            </template>
            <template #contractSigningDate="{ row }">
              <span>{{ row.contractSigningDate | parseTime('{y}-{m}-{d}') }}</span>
            </template>
            <template #operation="{ row }">
              <!-- <vxe-button size="mini" status="info" @click="openSubmit(row)">结算办理</vxe-button> -->
              <vxe-button size="mini" status="info" @click="openFinish(row)">结算完成</vxe-button>
            </template>
          </vxe-grid>
        </div>
        <vxe-pager background :current-page.sync="form.page" :page-size.sync="form.size" :total="total"
          :layouts="['Total', 'Sizes', 'PrevPage', 'JumpNumber', 'NextPage']" @page-change="pager">
        </vxe-pager>
      </div>
    </div>
    <SelectFromTableDialog ref="selectTable" title="结算单生成" submitBtn="生成并导出excel" :columns="settlementColumns"
      :tableData="settlementList" :total="settlementTotal" border="full" @search="getSettlementList"
      @pager="getSettlementList" @submit="exportSettlement" />
    <vxe-modal v-model="dialogVisible" title="合同确认完成" width="40%" :destroy-on-close="true">
      <Form ref="form" v-model="finishContractForm" :formOptions="finishContractFormOptions" />
      <div slots="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="finishContract">确 定</el-button>
      </div>
    </vxe-modal>
  </div>
</template>
<script>
import util from '../../util/util';
import IuapSearch from '/@/components/Iuap/IuapSearch.vue';
import SelectFromTableDialog from '/@/components/SelectFromTableDialog';
import VXETable from 'vxe-table';
import Form from '/@/components/PartForDialog/form.vue';
import * as ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
export default {
  components: { IuapSearch, SelectFromTableDialog, Form },
  data() {
    return {
      form: {
        contractId: this.$route.query.contractId,
        page: 1,
        size: 10,
      },
      columns: [
        {
          type: 'seq',
          width: 60,
          title: '序号',
          align: 'center',
        },
        {
          field: 'reportNumber',
          title: '报告编号',
          width: 180,
          editRender: {},
        },
        {
          field: 'entrustNumber',
          title: '委托编号',
          width: 180,
          editRender: {},
        },
        {
          field: 'entrustDate',
          title: '委托日期',
          width: 100,
          editRender: {},
          formatter({ cellValue }) {
            return util.parseTime(cellValue, '{y}-{m}-{d}');
          },
        },
        {
          field: 'itemName',
          title: '检测项目',
          width: 100,
          editRender: {},
        },
        {
          field: 'paramName',
          title: '检测参数',
          width: 100,
          editRender: {},
        },
        {
          field: 'detectQty',
          title: '数量',
          width: 100,
          editRender: {},
        },
        {
          field: 'salesUnit',
          title: '单位',
          width: 80,
          editRender: {},
        },
        {
          field: 'workingHours',
          title: '工时',
          width: 100,
          editRender: {},
        },
        {
          field: 'totalWorkingHours',
          title: '总工时',
          width: 100,
          editRender: {},
        },
        {
          field: 'contractPrice',
          title: '单价',
          width: 80,
          editRender: {},
        },
        {
          field: 'totalContractPrice',
          title: '合价',
          width: 80,
          editRender: {},
        },
        {
          field: 'submitReportTime',
          title: '出报告日期',
          width: 100,
          editRender: {},
          formatter({ cellValue }) {
            return util.parseTime(cellValue, '{y}-{m}-{d}');
          },
        },
        {
          field: 'sendReportTime',
          title: '发报告日期',
          width: 100,
          editRender: {},
          formatter({ cellValue }) {
            return util.parseTime(cellValue, '{y}-{m}-{d}');
          },
        },
        {
          field: 'isTimesheetCompleted',
          width: 130,
          title: '是否完成工时登记',
          editRender: {},
          formatter: ({ cellValue }) => {
            return this.formatBoolean(cellValue);
          },
        },
        {
          field: 'isSettled',
          title: '是否办理结算',
          width: 100,
          editRender: {},
          formatter: ({ cellValue }) => {
            return this.formatBoolean(cellValue);
          },
        },
        {
          field: 'remarks',
          title: '备注',
          width: 180,
          editRender: {},
        },
        {
          title: '操作',
          field: 'operation',
          width: 200,
          headerAlign: 'left',
          fixed: 'right',
          slots: { default: 'operation' },
        },
      ],
      tableData: [],
      settlementList: [],
      total: 0,
      fromData: [
        {
          name: '项目名称',
          key: 'projectName',
          type: 'input',
          value: this.$route.query.projectName,
          disabled: true,
        },
        {
          name: '委托方',
          key: 'companyName',
          type: 'input',
          disabled: true,
          value: this.$route.query.companyName,
        },
        {
          name: '合同状态',
          key: 'contractStatus',
          type: 'option',
          value: this.$route.query.contractStatus,
          disabled: true,
          options: [
            {
              label: '完成',
              value: 'COMPLETED',
            },

            {
              label: '未完成',
              value: 'IN_PROGRESS',
            },
          ],
        },
        {
          name: '报告编号',
          key: 'reportNumber',
          type: 'input',
          value: '',
        },
        {
          name: '检测项目',
          key: 'itemName',
          type: 'input',
          value: '',
        },
        {
          name: '出报告日期',
          key: 'submitReportTime',
          type: 'date',
          value: '',
        },
        {
          name: '发报告日期',
          key: 'sendReportTime',
          type: 'date',
          value: '',
        },
      ],
      settlementColumns: [
        {
          type: 'checkbox',
          field: 'checkbox',
          title: '',
          width: 60,
          editRender: {},
        },
        {
          field: 'reportNumber',
          title: '报告编号',
          editRender: {},
        },
        {
          field: 'entrustNumber',
          title: '委托编号',
          editRender: {},
        },
        {
          field: 'entrustDate',
          title: '委托日期',
          width: 100,
          editRender: {},
          formatter({ cellValue }) {
            return util.parseTime(cellValue, '{y}-{m}-{d}');
          },
        },
        {
          field: 'itemName',
          title: '检测项目',
          editRender: {},
        },
        {
          field: 'paramName',
          title: '检测参数',
          editRender: {},
        },
        {
          field: 'detectQty',
          title: '数量',
          editRender: {},
        },
        {
          field: 'salesUnit',
          title: '单位',
          editRender: {},
        },
        {
          field: 'contractPrice',
          title: '单价',
          editRender: {},
        },
        {
          field: 'totalContractPrice',
          title: '合计',
          editRender: {},
        },
      ],
      settlementTotal: 0,
      dialogVisible: false,
      finishContractForm: {
        contractId: this.$route.query.contractId,
        finishConfirmDate: null,
      },
      finishContractFormOptions: {
        column: 2,
        items: [
          {
            title: '合同完成时间',
            field: 'finishConfirmDate',
            type: 'date',
          },
        ],
      },
    };
  },
  filters: {
    getContractStatus(val) {
      return val === 'COMPLETED' ? '完成' : '未完成';
    },
  },
  created() {
    this.getList();
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    formatBoolean(val) {
      return val ? '是' : '否';
    },
    async getList() {
      await this.$api.getSampleOrderItemCountPage(this.form).then((res) => {
        try {
          const { list, total } = res.data;
          this.tableData = list.map((item) => {
            return {
              ...item,
              operation: '结算办理',
            };
          });
          // console.log(this.tableData);
          this.total = total;
        } catch { }
      });
    },
    async getSettlementList(params) {
      await this.$api.getSampleOrderItemCountPage({ ...this.form, ...params }).then((res) => {
        try {
          const { list, total } = res.data;
          // console.log(res.data);
          this.settlementList = list.map((item) => {
            return {
              ...item,
              checkbox: '勾选',
            };
          });
          this.settlementTotal = total;
        } catch { }
      });
    },
    pager({ currentPage, pageSize }) {
      this.form.page = currentPage;
      this.form.size = pageSize;
      this.getList();
    },
    search() {
      this.form.page = 1;
      this.getList();
    },
    searchFn(e) {
      this.fromData.forEach((item) => {
        this.form[item.key] = item.value;
      });
      this.form.page = 1;
      this.getList();
    },
    reset() {
      this.form = {
        page: 1,
        size: 10,
      };
      this.getList();
    },
    add() {
      this.getSettlementList();
      this.$refs.selectTable.dialogVisible = true;
    },
    finish() {
      this.dialogVisible = true;
    },
    finishContract() {
      if (!this.finishContractForm.finishConfirmDate) {
        VXETable.modal.message({
          content: '请选择完成合同时间',
          status: 'error',
        });
        return;
      }
      this.$api.finishContract(this.finishContractForm).then((res) => {
        if (res.code === 0) {
          VXETable.modal.message({
            content: '合同完成',
            status: 'success',
          });
          this.back();
        }
      });
    },
    // async exp() {
    //   const result = await this.getAllList();
    //   this.$refs.table.exportData({
    //     filename: '',
    //     sheetName: '',
    //     type: 'xlsx',
    //     useStyle: true,
    //     columnFilterMethod: (column, $columnIndex) => {
    //       return !(column.$columnIndex === 0 || column.$columnIndex === 5);
    //     },
    //     data: result,
    //   });
    // },
    async exportSettlement(result) {
      // 方法1
      console.log(result, 233)
      const sampleIds = result.map(item => item.sampleId);
      await this.$api.generateSettleOrder({ sampleIds }).then((res) => {
        const blob = new Blob([res]);
        saveAs(blob, '检测报告.xlsx');
        VXETable.modal.message({
          content: '下载成功',
          status: 'success',
        });
      });

      // 方法2.掉后端接口导出
      // 1. 首先，获取所有的sampleIds
      // const sampleIds = result.map(item => item.sampleId);
      // console.log('sampleIds', sampleIds);
      // try {
      //   // 2. 调用后端接口，传递sampleIds作为参数
      //   const response = await this.$api.generateSettleOrder({ sampleIds });
      //   console.log('response', response);
      //   // 3. 在这里处理后端返回的文件流
      //   // const blob = new Blob([response], { type: 'text/csv' });
      //   // 4. 使用 URL.createObjectURL 创建一个临时链接，然后模拟点击下载
      //   const url = window.URL.createObjectURL(response);
      //   const link = document.createElement('a');
      //   link.href = url;
      //   link.download = '结算单.csv';
      //   document.body.appendChild(link);
      //   link.click();
      //   document.body.removeChild(link);
      //   // 5. 释放 URL.createObjectURL 创建的临时链接
      //   window.URL.revokeObjectURL(url);
      // } catch (error) {
      //   console.error('导出结算单失败:', error);
      // }

      // 方法3：使用前端vxe table方法导出
      // result.forEach((item, i) => {
      //   item.id = item.id + i;
      // });
      // this.$refs.selectTable.$refs.table.exportData({
      //   filename: '导出结算单',
      //   type: 'xlsx',
      //   useStyle: true,
      //   data: result,
      //   columnFilterMethod: (column, $columnIndex) => {
      //     return column.$columnIndex !== 0;
      //   },
      //   sheetMethod: ({ options, workbook, worksheet, columns }) => {
      //     let fields = ['reportNumber', 'entrustNumber', 'itemName'];
      //     const indexes = fields.map((key, i) => {
      //       return columns.findIndex((column) => column.field === key);
      //     });
      //     const fixRowIndex = 2;
      //     const fixColumnIndex = 1;
      //     const mergeCells = [];
      //     options.data.forEach((row, i) => {
      //       const lastItem = mergeCells[mergeCells.length - 1];
      //       if (lastItem?.sampleId !== row.sampleId) {
      //         mergeCells.push({
      //           rowStart: lastItem ? lastItem?.rowEnd + 1 : fixRowIndex,
      //           rowEnd: i + fixRowIndex,
      //           sampleId: row.sampleId,
      //         });
      //       } else {
      //         lastItem.rowEnd = i + fixRowIndex;
      //       }
      //     });
      //     indexes.forEach((index) => {
      //       mergeCells.forEach((cell) => {
      //         worksheet.mergeCells(cell.rowStart, index + fixColumnIndex, cell.rowEnd, index + fixColumnIndex);
      //       });
      //     });
      //   },
      // });


    },

    async openSubmit(row) {
      const type = await VXETable.modal.confirm(`是否确定办理结算？`);
      if (type === 'confirm') {
        this.submitSettlement(row);
      }
    },
    async openFinish(row) {
      const type = await VXETable.modal.confirm(`是否确定结算完成？`);
      if (type === 'confirm') {
        this.finishSettlement(row);
      }
    },
    submitSettlement(row) {
      this.$api.settleSampleOrderBatch({ sampleIds: [row.sampleId] }).then((res) => {
        VXETable.modal.message({
          content: '办理结算成功',
          status: 'success',
        });
      });
    },
    finishSettlement(row) {
      this.$api.settleCompleteSampleOrder({ sampleId: row.sampleId }).then((res) => {
        VXETable.modal.message({
          content: '结算完成',
          status: 'success',
        });
      });
    },
    checkFileList(row) {
      const item = row.contractFile;
      const a = document.createElement('a');
      a.target = '_blank';
      a.href = item.fileUrl;
      a.click();
    },
    rowspanMethod({ row, _rowIndex, column, visibleData }) {
      let fields = ['reportNumber', 'entrustNumber', 'itemName', 'operation', 'entrustDate', 'submitReportTime', 'sendReportTime', 'isTimesheetCompleted', 'isSettled'];
      let cellValue = row[column.property];
      if (cellValue !== null || cellValue !== undefined || cellValue !== '' && fields.includes(column.property)) {
        let prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.property] + '' + prevRow.sampleId === cellValue + '' + row.sampleId) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] + '' + nextRow.sampleId === cellValue + '' + row.sampleId) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.vxe-button.type--button.theme--primary {
  height: 28px;
  font-size: 12px;
  background-color: rgb(31, 143, 255) !important;
  border-color: rgb(31, 143, 255) !important;
}

.vxe-button.type--button.size--mini {
  height: 21px;
  line-height: 21px;
  font-size: 12px;
}

.vxe-form--item-title-label {
  font-size: 13px;
}

.tableListBox {
  height: 100vh;

  .tableList {
    ::v-deep {
      .vxe-form.outForm {
        .vxe-form--item-content {
          width: 280px;
        }

        .vxe-form--item {
          width: 28%;
        }

        .last-item {
          width: 16%;
          text-align: right;
        }
      }

      .vxe-table--body-wrapper {
        overflow-y: auto !important;
      }

      // .vxe-table--main-wrapper {
      //   height: calc(100vh - 70px);
      //   .vxe-table--body-wrapper {
      //     height: calc(100% - 50px);
      //   }
      // }
      .table-normal .vxe-header--row {
        height: 30px;
      }

      // .vxe-form .vxe-form--item .vxe-form--item-inner .vxe-form--item-content .vxe-input {
      //   height: 26px !important;
      //   line-height: 26px !important;
      // }
      .vxe-table--render-default .vxe-header--column:not(.col--ellipsis) {
        padding: 0 !important;
        font-size: 13px;
      }

      .vxe-table--render-default .vxe-body--column.col--ellipsis {
        height: 35px;
        font-size: 13px;
      }

      .vxe-button.type--text.theme--info {
        color: #06f;
        cursor: pointer;
        line-height: 1;
      }

      .vxe-button.type--button.size--mini.theme--info:not(.is--disabled) {
        background-color: #505766 !important;
        border-color: #505766 !important;
        // height: 20px;
        border-radius: 2px;
      }

      .vxe-button.type--button.size--small.theme--info:not(.is--disabled) {
        background-color: #505766 !important;
        border-color: #505766 !important;
        // height: 26px;
        border-radius: 2px;
      }

      .vxe-pager--wrapper button.is--active {
        background-color: #adb4bc !important;
        border-color: #adb4bc !important;
        box-shadow: none;
      }

      // .vxe-input {
      //   height: 20px;
      // }
      .vxe-pager--wrapper button {
        // width: 18px;
        // height: 18px;
        // line-height: 18px;
        // font-size: 12px;
      }

      // .vxe-pager {
      //   display: flex;
      //   position: absolute;
      //   bottom: 0;
      //   width: 100%;
      //   justify-content: flex-end;
      // }
    }
  }
}
</style>
